package com.future.mayi.fragment;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.future.baselib.utils.CommonUtils;
import com.future.baselib.utils.ToastUtil;
import com.future.baselib.utils.statusbarlibrary.StatusBarUtils;
import com.future.mayi.R;
import com.future.mayi.activity.GoodsActivity;
import com.future.mayi.model.GoodsModel;
import com.future.mayi.model.SpecListModel;
import com.future.mayi.model.interfaces.GoodsSelectChangeListener;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.PriceUtils;
import com.future.mayi.view.GoodsSelectView;

public class GoodsSelectFragment extends BaseFullBottomSheetFragment implements View.OnClickListener, GoodsSelectChangeListener {


    private View contentView;
    private boolean viewChange;

    private TextView tvPrice, tvRemaining, tvSub, tvAdd, tvEnter;
    private EditText tvNum;
    private ScrollView scrollView;
    private ImageView ivImg, ivClose;
    private GoodsSelectView gsv;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.dialog_goods_select, container, false);
            setTopOffset((int) (CommonUtils.getScreenSize(getActivity())[1] * 0.4f));
            viewChange = true;
        } else {
            ViewGroup parent = (ViewGroup) contentView.getParent();
            if (parent != null) {
                parent.removeView(contentView);
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            StatusBarUtils.setStatusBarStyle(getDialog().getWindow(), true);
        return contentView;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (viewChange) {
            ivImg = view.findViewById(R.id.iv_img);
            ivClose = view.findViewById(R.id.iv_close);
            tvPrice = view.findViewById(R.id.tv_price);
            tvRemaining = view.findViewById(R.id.tv_remaining);
            tvSub = view.findViewById(R.id.tv_sub);
            tvNum = view.findViewById(R.id.tv_num);
            scrollView = view.findViewById(R.id.scroll_view);
            tvNum.setCursorVisible(false);
            tvNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!TextUtils.isEmpty(tvNum.getText()))
                        tvNum.setSelection(tvNum.getText().toString().length());
                }
            });
//            tvNum.clearFocus();
            tvAdd = view.findViewById(R.id.tv_add);
            tvEnter = view.findViewById(R.id.tv_enter);
            gsv = view.findViewById(R.id.gsv);
            viewChange = false;
            gsv.setListener(this);
            ivClose.setOnClickListener(this);
            tvSub.setOnClickListener(this);
            tvAdd.setOnClickListener(this);
            tvEnter.setOnClickListener(this);


        }
        setData(cacheGoodsModel, addCart);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_sub: {
                if (TextUtils.isEmpty(tvNum.getText())) {
                    tvNum.setText("1");
                    return;
                }
                int num = Integer.valueOf(tvNum.getText().toString()) - 1;
                if (num <= 0) num = 1;
                tvNum.setText(String.valueOf(num));
            }
            break;
            case R.id.tv_add: {
                if (TextUtils.isEmpty(tvNum.getText())) {
                    tvNum.setText("1");
                    return;
                }
                int num = Integer.valueOf(tvNum.getText().toString()) + 1;
                int max = specListModel == null ? goodsModel.getDetail().getStock() : specListModel.getForm().getStock_num();
                if (num > max) {
                    ToastUtil.getInstance().show(getActivity(), "数量超出范围");
                    return;
                }
                if (num <= 0) num = 1;
                tvNum.setText(String.valueOf(num));
            }
            break;
            case R.id.tv_enter:
                enter();
                break;
        }

    }

    private void enter() {
        if (goodsModel == null) return;
        if (goodsModel.getSpecData() != null && specListModel == null) {
            ToastUtil.getInstance().show(getActivity(), "请选择");
            return;
        }
        if (TextUtils.isEmpty(tvNum.getText().toString())) {
            ToastUtil.getInstance().show(getActivity(), "请选择商品数量");
            return;
        }
        int num = Integer.valueOf(tvNum.getText().toString());
        if (num == 0) {
            ToastUtil.getInstance().show(getActivity(), "请选择商品数量");
            return;
        }
        ((GoodsActivity) getActivity()).buy(specListModel, num, addCart);
        dismiss();
    }


    private GoodsModel cacheGoodsModel;
    private GoodsModel goodsModel;
    private boolean addCart;


    public void setData(GoodsModel goodsModel, boolean addCart) {
        this.addCart = addCart;
        if (gsv == null) {
            this.cacheGoodsModel = goodsModel;
            return;
        }
        if (this.goodsModel == goodsModel) return;
        this.goodsModel = goodsModel;
        if (goodsModel == null || goodsModel.getSpecData() == null)
            gsv.setVisibility(View.GONE);
        else
            gsv.setData(goodsModel.getSpecData().getSpec_attr(), goodsModel.getSpecData().getSpec_list());

        gsv.post(new Runnable() {
            @Override
            public void run() {
                int height = CommonUtils.getScreenSize(getContext())[0] - CommonUtils.dip2px(getContext(), 280);
                if (height < 0) {
                    height = CommonUtils.dip2px(getContext(), 100);
                }
                int gsvHeight = gsv.getMeasuredHeight() + CommonUtils.dip2px(getContext(), 280) + CommonUtils.getStatusBarHeight(getContext());
                int maxHeight = CommonUtils.getScreenSize(getContext())[0];
                if (gsvHeight > maxHeight) {
                    scrollView.getLayoutParams().height = height;
                }
            }

        });

        tvEnter.setText(addCart ? "确认" : "立即购买");
        onGoodsSelect(null, null);
    }


    private SpecListModel specListModel;

    @Override
    public void onGoodsSelect(GoodsSelectView view, SpecListModel model) {
        this.specListModel = model;
        if (specListModel == null) {
            tvPrice.setText(PriceUtils.getPriceText2(goodsModel.getDetail().getGoods_price()));
            tvRemaining.setText(String.valueOf(goodsModel.getDetail().getStock()));
            HCUtils.loadWebImg(getActivity(), ivImg, goodsModel.getDetail().getImage());
            tvNum.setText("1");
            if (goodsModel.getDetail().getStock() > 0) {
                tvEnter.setBackgroundColor(getResources().getColor(R.color.main_color));
                tvEnter.setText(addCart ? "确认" : "立即购买");
                tvEnter.setEnabled(true);
            } else {
                tvEnter.setBackgroundColor(getResources().getColor(R.color.bg_E8E8E8));
                tvEnter.setText("商品已售罄");
                tvEnter.setEnabled(false);
            }
        } else {
            tvPrice.setText(PriceUtils.getPriceText2(specListModel.getForm().getGoods_price()));
            tvRemaining.setText(String.valueOf(specListModel.getForm().getStock_num()));
            HCUtils.loadWebImg(getActivity(), ivImg, specListModel.getForm().getSpec_image());
            if (specListModel.getForm().getStock_num() > 0) {
                tvEnter.setBackgroundColor(getResources().getColor(R.color.main_color));
                tvEnter.setText(addCart ? "确认" : "立即购买");
                tvEnter.setEnabled(true);
            } else {
                tvEnter.setBackgroundColor(getResources().getColor(R.color.bg_E8E8E8));
                tvEnter.setText("商品已售罄");
                tvEnter.setEnabled(false);
            }
            if (TextUtils.isEmpty(tvNum.getText())) {
                tvNum.setText("1");
                return;
            }
            int num = Integer.valueOf(tvNum.getText().toString());
            if (num == 0) return;
            if (num > specListModel.getForm().getStock_num())
                tvNum.setText(String.valueOf(specListModel.getForm().getStock_num()));
        }
    }


}
